package com.ytkj.digitalConstruction.rabbit;

import java.util.UUID;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.util.StringUtils;
import com.ytkj.digitalConstruction.enums.exception.DingExceptionEnum;
import com.ytkj.digitalConstruction.enums.exception.ExceptionMsgEnum;
import com.ytkj.digitalConstruction.exception.CustomException;

/**
 * 向rabbitMQ中发送消息的类
 * 
 * @author yf
 * @author momei
 */
@Component
public class Sender implements ConfirmCallback, ReturnCallback {

	Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	private RabbitTemplate rabbitTemplate;

	@PostConstruct
	public void init() {
		rabbitTemplate.setConfirmCallback(this);
		rabbitTemplate.setReturnCallback(this);
	}

	/**
	 * 向队列发送消息
	 * 
	 * @param msg
	 *            消息的JSON格式字符串
	 * @param routingkey
	 *            与队列绑定的routingkey,用户明确发送的目标队列
	 */
	public String send(String msg, String routingkey) {
		if (StringUtils.isEmpty(msg) || StringUtils.isEmpty(routingkey)) {
			throw new CustomException(ExceptionMsgEnum.PARAM_INVALID);
		}

		CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
		log.info("开始发送消息 : " + msg);
		Object obj = rabbitTemplate.convertSendAndReceive("directExchange", routingkey, msg, correlationId);
		if (obj == null) {
			log.error("Sender send Exception: response is null!");
			throw new CustomException(DingExceptionEnum.RESPONSE_ERROR);
		}
		String response = obj.toString();
		if (response == null) {
			log.error("Sender send Exception: response is null!");
			throw new CustomException(DingExceptionEnum.RESPONSE_ERROR);
		}
		log.info("结束发送消息 : " + msg);
		log.info("消费者响应 : " + response + " 消息处理完成");

		return response;
	}

	@Transactional
	@Override
	public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
		log.info(message.getMessageProperties().getCorrelationIdString() + "发送失败!");
	}

	@Override
	public void confirm(CorrelationData correlationData, boolean ack, String cause) {
		if (ack) {
			log.info("消息发送成功:" + correlationData);
		} else {
			log.info("消息发送失败:" + cause);
		}
	}

}
